package org.csu.mypetstorebackstage.AccessProvider;

import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.csu.mypetstorebackstage.AccessToken.ProviderToken;
import org.csu.mypetstorebackstage.domain.Account;
import org.csu.mypetstorebackstage.domain.Manager;
import org.springframework.stereotype.Component;

import java.io.IOException;


@Component
public class AccessProvider {
    public String getToken(ProviderToken providerToken){
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");

        OkHttpClient client = new OkHttpClient();

            RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(providerToken));
            Request request = new Request.Builder()
                    .url("https://gitee.com/oauth/token?grant_type=authorization_code&code=" +  providerToken.getCode() + "&client_id=" +  providerToken.getClient_id() + "&redirect_uri=" +  providerToken.getRedirect_url() + "&client_secret=" +  providerToken.getClient_secret())
                    .post(body)
                    .build();
            try (Response response = client.newCall(request).execute()) {
                String string = response.body().string();

                String s1 = string.split(":")[1];
                String s2 = s1.split("\"")[1];

                System.out.println(string);
                return s2;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
    }

    public Manager getManager(String Token) {
        OkHttpClient client = new OkHttpClient();

            Request request = new Request.Builder()
                    .url("https://gitee.com/api/v5/manager?access_token=" + Token)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                String string = response.body().string();
                Manager manager = JSON.parseObject(string, Manager.class);

                return manager;
            }
            catch (IOException e){}
            return  null;
    }
}
